// 初始化列表
var grid_selector = "";
var $grid_selector = "";
var pager_selector = "";
var parent_column = "";
var colNames = "";
var widthFunc = "";
var colModels = "";
//=========================================================================================================================================
// 初始化列表
var grid_selector1 = "";
var $grid_selector1 = "";
var pager_selector1 = "";
var parent_column1 = "";
var colNames1 = "";
var widthFunc1 = "";
var colModels1 = "";
$(document).ready(function () {
    $('#resourceName').click(function () {
        // 初始化列表
        grid_selector = '#grid-table';
        $grid_selector = $(grid_selector);
        pager_selector = '#grid-pager';
        parent_column = $grid_selector.closest('[class*="col-"]');
        colNames = [
            '资源分类',
            '资源名称',
            '资源IP',
            'domain',
            'uuid',
            'kbpPath'
        ];
        widthFunc = parent_column.width() / colNames.length;
        colModels = [
            {name: 'classNAME', index: 'classNAME', hideWidth: 300},
            {name: 'name', index: 'name', hideWidth: 300},
            {name: 'ip', index: 'ip', hideWidth: 300},
            {name: 'domain', index: 'domain', hideWidth: 300},
            {name: 'uuid', index: 'uuid', hideWidth: 300},
            {name: 'kbpPath', index: 'kbpPath', hidden: true},
        ];
        // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
        $(document).on('show.bs.modal', '.modal', function () {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        }).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
            $('#kpiName').val(" ");
            initKbpTable();
        });
        openKbpSelector();
    });
    //当前页面打开窗口的尺寸
    window.onresize = function () {
        changeFrameHeight();
    };
    changeFrameHeight();
});
//=========================================================================================================================================
$(document).ready(function () {
    $('#kpiName').click(function () {
        var name = $("#resourceName").val();
        if (name != null && name != " " && name.length != 0) {
            // 初始化列表
            grid_selector1 = '#grid-table1';
            $grid_selector1 = $(grid_selector1);
            pager_selector1 = '#grid-pager1';
            parent_column1 = $grid_selector1.closest('[class*="col-"]');
            colNames1 = [
                'KBP编码',
                'kpiId',
                '指标是否线性',
                '指标名称',
                '指标ID'
            ];
            widthFunc1 = parent_column1.width() / colNames1.length;
            colModels1 = [
                {name: 'className', index: 'className', hidden: true},
                {name: 'kpiId', index: 'kpiId', hidden: true},
                {name: 'kpiType', index: 'kpiType', hidden: true},
                {name: 'kpiName', index: 'kpiName', hideWidth: 300},
                {name: 'kpiCode', index: 'kpiCode', hideWidth: 300}

            ];
            // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
            $(document).on('show.bs.modal', '.modal', function () {
                var zIndex = 1040 + (10 * $('.modal:visible').length);
                $(this).css('z-index', zIndex);
                setTimeout(function () {
                    $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
                }, 0);
            }).on('shown.bs.modal', function () {// 当模态框对用户可见时触发（将等待 CSS 过渡效果完成）
                reloadJqGrid1();
                initKbpTable1();
            });
            openTable();
        } else {
            $(this).dynamicPop('必须先选择资源!');
        }
    });
    //当前页面打开窗口的尺寸
    window.onresize = function () {
        changeFrameHeight1();
    };
    changeFrameHeight1();
});

//=========================================================================================================================================
function changeFrameHeight() {
    var mainIframeHeight = $(window).height();
    var systemViewIframeHeight = mainIframeHeight - 112;
    $('#systemViewIframe').height(systemViewIframeHeight);
}

function changeFrameHeight1() {
    var mainIframeHeight = $(window).height();
    var systemViewIframeHeight = mainIframeHeight - 72;
    $('#systemViewIframe').height(systemViewIframeHeight);
}

function initKbpTable() {
    $grid_selector.jqGrid({
        url: ctx + '/KbpResourceData/queryPageListType',
        mtype: 'post',
        datatype: 'json',
        height: '100%',
        colNames: colNames,
        colModel: colModels,
        autowidth: true,
        altRows: true,
        rownumbers: true,
        viewrecords: true,
        multiselect: true,
        multiboxonly: true,
        rowNum: rowNum,
        rowList: rowList,
        sortname: 'ciId',
        pager: pager_selector,
        sortorder: 'asc',
        jsonReader: jsonReader,
        beforeRequest: function () {
            var postData = {};
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                // console.log($this.val());
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            // 获取KBP树节点
            var selectedItems = $('#kbpTreeview').tree('selectedItems');
            if (isNotEmpty(selectedItems)) {
                postData['classNAME'] = selectedItems[0].additionalParameters.id;
            } else {
                postData['classNAME'] = null;
            }
            $.extend($grid_selector.getGridParam('postData'), postData);
        },
        loadComplete: function () {
            setTimeout(function () {
                $grid_selector.jqGrid('setGridParam', parent_column.width());
            }, 20);
        }
    });
}

function initKbpTable1() {
    $grid_selector1.jqGrid({
        url: ctx + '/Forecast/queryPageListForceCast',
        mtype: 'post',
        datatype: 'json',
        height: '100%',
        colNames: colNames1,
        colModel: colModels1,
        autowidth: true,
        altRows: true,
        rownumbers: true,
        viewrecords: true,
        multiselect: true,
        multiboxonly: true,
        rowNum: rowNum,
        rowList: rowList,
        pager: pager_selector1,
        sortname: 'kpiCode',
        sortorder: 'asc',
        jsonReader: jsonReader,
        beforeRequest: function () {
            var postData = {};
            $('#queryPanel1').find('[name^="search."]').each(function () {
                var $this = $(this);
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            $.extend($grid_selector1.getGridParam('postData'), postData);
        },
        loadComplete: function () {
            setTimeout(function () {
                $grid_selector1.jqGrid('setGridWidth', parent_column1.width());
            }, 20);
        }
    });
}

function isNotEmpty(obj) {
    if (obj != null && obj != '' && obj != undefined) {
        return true;
    }
    return false;
}

/*点击按钮展示KBP树的节点*/
function openKbpSelector() {
    //加載KBP
    if (!$('#kbpTreeview').html()) {
        $('#kbpTreeview').ace_tree({
            dataSource: remoteKbpDateSource,
            loadingHTML: '<div class="tree-loading"><i class="ace-icon fa fa-refresh fa-spin blue"></i></div>',
            'open-icon': 'ace-icon fa fa-chevron-down',
            'close-icon': 'ace-icon fa fa-chevron-right',
            'itemSelect': true,
            'folderSelect': false,
            'multiSelect': false,
            'selected-icon': null,
            'unselected-icon': null,
            'folder-open-icon': 'ace-icon tree-plus',
            'folder-close-icon': 'ace-icon tree-minus',
            'cacheItems': false
        }).on('selected.fu.tree', function (event, data) {
            //点击KBP子节点查询所包含的资源名称
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                $this.val("");
            });
            $("#grid-table").trigger("reloadGrid");
        }).on('deselected.fu.tree', function (event, data) {
            $("#grid-table").trigger("reloadGrid");
        });
    }
    $.launchDialog('popup');
}

/*点击选择指标按钮展示KPI所有指标*/
function openTable() {
    if (!$('#grid-table1').html()) {
        $("#grid-table1").trigger("reloadGrid");
        var $this = $(this);
        $this.val("");
    }
    $.launchDialog('popup1');
}

/*点击确认触发的操作*/
$('#confirm').click(function () {
    //获取选中行的id
    var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
    if (rowIds == null || rowIds.length == 0) {
        $(this).dynamicPop('请选择一条记录!');
    } else if (rowIds.length > 1) {
        $(this).dynamicPop(' 不能选择多条记录, 请选择一条记录!');
    } else {
        var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
        //UNIT_ID
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        $("#resourceName").val(rowData.name + "(" + rowData.ip + ")");
        // 最后关闭该窗口
        $('#popup').modal('hide');
    }
    // alert(url);
});

/*点击确认触发的操作1*/
$('#confirm1').click(function () {
    //获取选中行的id
    var rowIds = $grid_selector1.jqGrid('getGridParam', 'selarrrow');
    if (rowIds == null || rowIds.length == 0) {
        $(this).dynamicPop('请选择一条记录!');
    } else if (rowIds.length > 1) {
        $(this).dynamicPop(' 不能选择多条记录, 请选择一条记录!');
    } else {
        var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
        //UNIT_ID
        var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
        $("#kpiName").val(rowData.kpiName);
        // 最后关闭该窗口
        $('#popup1').modal('hide');
    }
    // alert(url);
});

//显示隐藏查询条件
$('#searBtn').click(function () {
    $(this).find('i').toggleClass('fa-arrow-down');
    $(this).find('i').toggleClass('fa-arrow-up');
});

//查询按钮
$('#searchBtn').click(function () {
    $grid_selector.trigger('reloadGrid', [{page: 1}]);
});

//查询按钮1
$('#searchBtn11').click(function () {
    $grid_selector1.trigger('reloadGrid', [{page: 1}]);
});

// 重置查询表单
$('#resetBtn').click(function () {
    $('#queryPanel').find(':input(:text)').each(function () {
        $(this).val('');
    });
    $('#queryPanel').find('input[type=checkbox],input[type=radio]').each(function () {
        $(this).removeAttr('checked');
    });
    reloadJqGrid('json');
});

// 重置查询表单1
$('#resetBtn11').click(function () {
    $('#queryPanel1').find(':input(:text)').each(function () {
        $(this).val('');
    });
    $('#queryPanel1').find('input[type=checkbox],input[type=radio]').each(function () {
        $(this).removeAttr('checked');
    });
    reloadJqGrid1('json');
});


// 重置iframe输入框
$('#resetBtn1').click(function () {
    $('#input').find(':input(:text)').each(function () {
        $(this).val('');
    });
});


//查询按钮的操作
$('#searchBtn1').click(function () {
    var name = $('#resourceName').val();
    var name1 = $('#kpiName').val();
    var Id = "PM-00-01-004-03";
    var aa = 123;
    var $grid_selector1 = $(grid_selector1);
    var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
    var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
    var kpiType = rowData.kpiType;//0 为线性指标(持续增长)1为否
    if (name == null || name.length == 0 || name == " ") {
        $(this).dynamicPop('请选择资源!');
    } else if (name1 == null || name1.length == 0 || name1 == " ") {
        $(this).dynamicPop('请选择指标!');
    } else if (kpiType == 0 && name != null && name != " " && name.length != 0) {
        var rowId111 = $grid_selector.jqGrid('getGridParam', 'selrow');
        var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
        var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
        var rowData111 = $("#grid-table").jqGrid('getRowData', rowId111);
        var unitId = rowData111.classNAME + ":" + rowData111.domain + ":" + rowData111.uuid;
        var kpiCode = rowData.kpiCode;
        var kpiName = encodeURI(encodeURI(rowData.kpiName));
        var kbpPath = rowData111.kbpPath;
        var url = ctx + kbpPath + "/" + kpiCode + "/" + kpiName + "/" + unitId + "/" + Id + "/" + aa;
        $('#systemViewIframe').attr('src', url);
    } else if (kpiType == 1 && name != null && name != " " && name.length != 0 && name1 != null && name1 != " " && name1.length != 0) {
        var rowId111 = $grid_selector.jqGrid('getGridParam', 'selrow');
        var rowId = $grid_selector1.jqGrid('getGridParam', 'selrow');
        var rowData = $("#grid-table1").jqGrid('getRowData', rowId);
        var rowData111 = $("#grid-table").jqGrid('getRowData', rowId111);
        var unitId = rowData111.classNAME + ":" + rowData111.domain + ":" + rowData111.uuid;
        var kpiCode = rowData.kpiCode;
        var kpiName = encodeURI(encodeURI(rowData.kpiName));
        var kbpPath = rowData111.kbpPath;
        var url = ctx + kbpPath + "/" + kpiCode + "/" + kpiName + "/" + unitId;
        $('#systemViewIframe').attr('src', url);
    }
});

// 刷新JqGrid列表
function reloadJqGrid(datatype) {
    $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
}

// 刷新JqGrid1列表
function reloadJqGrid1(datatype) {
    $grid_selector1.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
}
